package com.hmdp.filter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;

//@WebFilter("/**")
public class RefreshTokenFilter implements Filter {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        String token = ((HttpServletRequest)request).getHeader("authorization");
        String key = LOGIN_USER_KEY + token;
        if (StrUtil.isBlank(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        if (userMap.isEmpty()) {
            ((HttpServletResponse)response).setStatus(401);
            return;
        }
        UserDTO user = new UserDTO();
        BeanUtil.fillBeanWithMap(userMap, user, true);

        UserHolder.saveUser(user);

        stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.MINUTES);

        System.out.println("userId:" + user.getId());
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
